package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.repository.ArticleDocumentRepository;
import com.heima.article.service.QueryByThreadService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.pojos.ArticleDocument;
import com.heima.utils.common.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : Liu
 * @date : 2022/1/6 0006 21:02
 */
@Service
public class QueryByThreadServiceImpl implements QueryByThreadService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ArticleDocumentRepository articleDocumentRepository;

    @Override
    public void queryByThread() {
        // 每条线程执行的数量
        int count = 2;
        // 数据总条数
        ///int listSizeCount = apArticleMapper.querySize();
        QueryWrapper<ApArticle> wrapper = new QueryWrapper<>();
        Integer integer = apArticleMapper.selectCount(wrapper);
        int listSizeCount = integer;
        // 开启的线程数
        int runSize = listSizeCount / count;
        // 多出来的条数
        int runMostCount = listSizeCount % count;
        if (runMostCount != 0) {
            runSize ++;
        }

        // 创建一个线程池，数量和开启线程的数量一样
        ExecutorService executor = Executors.newFixedThreadPool(runSize);
        // 计算sql语句中每个分页查询的起始和结束数据下标
        // 循环创建线程
        //此处调用具体的查询方法
        System.out.println("开始查询");
        for (int i = 0; i < runSize; i++) {
            int index = i * count;
            int num;
            if (i == runSize - 1) {
                num = runMostCount;
            } else {
                num = count;
            }
            executor.execute(() -> {
                try {
                    //查询的结果如何保存下来，会不会存在覆盖的问题
                    System.out.println("每次查询的下标:" + index + ",条数:" + num + "\n当前线程Id" + Thread.currentThread().getName());
                    List<ApArticle> articleList = apArticleMapper.limitApArticle(index, num);
                    //保存到ES
                    List<ArticleDocument> articleDocuments = BeanHelper.copyWithCollection(articleList, ArticleDocument.class);
                    articleDocumentRepository.saveAll(articleDocuments);
                } catch (Exception e) {
                    System.out.println("查询失败" + e);
                }
            });
        }
        // 执行完关闭线程池
        executor.shutdown();
    }
}
